//
//  OMShoppingCartViewController.m
//  OMENGO
//
//  Created by 梁尚嘉 on 2016/12/6.
//  Copyright © 2016年 Kamfat. All rights reserved.
//

#import "OMShoppingCartViewController.h"
#import "OMShoppingCartGoodTableCell.h"
#import "OMShoppingcartHeaderView.h"
#import "OMShoppingCartGoodTableCell.h"
#import "OMCartProduct.h"

#import "OMProduct.h"
#import "OMCheapModel.h"
#import "OMDeliveryInfo.h"

#import "OMCommonAddressTableCell.h"
#import "OMCartPreferentialActivityFooter.h"
#import "OMDeliveryAddressViewController.h"
#import "OMOrderBookResponse.h"

@interface OMShoppingCartViewController () <OMConsumerGoodTableCellDelegate,OMShoppingcartHeaderViewDelegate,OMDeliveryAddressViewCtrlDelegate>
@property (nonatomic, strong) NSMutableArray <OMCartSection *>*goodSections;

@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) UIButton *checkBoxBtn;
@property (nonatomic, strong) UILabel *prizeLabel;
@property (nonatomic, strong) NSMutableDictionary *sectionSelectionDict;
@property (nonatomic, strong) NSMutableDictionary *selectionDict;
@property (nonatomic, assign) BOOL isAllSelect;


@property (nonatomic, strong) NSArray <OMCheapModel*> *coupons;
@property (nonatomic, strong) NSArray <OMProduct*>*products;
@property (nonatomic, strong) OMDeliveryInfo *deliveryInfo;
@property (nonatomic, strong) OMCommonAddressTableCell *addressCell;
@end

@implementation OMShoppingCartViewController
- (instancetype)init
{
    if (self = [super init]) {
    }
    return self;
}

UIView *bottomBar = nil;
- (void)viewDidLoad {

    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self configure];

    [self setupFooter];

    @weakify(self);
    [SMNotificationMonitorRACSignal(KTLoginSuccessNotificationKey) subscribeNext:^(NSNotification *notification) {
        @strongify(self);
        [self reload];
//        [self getDefaultDeliveryAddress];
    }];

    [SMNotificationMonitorRACSignal(OM_NOTIFICATION_KEY_LOGOUT_SUCCESS) subscribeNext:^(id x) {
        @strongify(self);
        [self viewWillAppear:YES];
    }];

//    [self getDefaultDeliveryAddress];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self reload];
}

- (void)reload
{
    self.loading = YES;
    [self startAnimating:YES];
    bottomBar.hidden = true;
    [self getCartProductList];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

}

- (void)reloadDataFromNetWork
{
    [self getCartProductList];
}


/**
 获取默认地址
 */
- (void)getDefaultDeliveryAddress
{
    if (![Storage isLogin]) {
        self.deliveryInfo = nil;
        return;
    }
    [KTHttpUtils GET_NOCACHE:@"receiver/findDefault.jhtml"
                  parameters:nil
                    progress:nil
                  completion:^(id responseObject, BOOL isSuccess, NSString *message) {
                      self.deliveryInfo = [OMDeliveryInfo mj_objectWithKeyValues:responseObject[OMDatumKey]];
                  }];
}



/**
 从服务器获取购物车信息
 */
- (void)getCartProductList
{
    NSString *cartKey = KTSystemStorageSingleton.cartKey;
    NSDictionary *parameters = cartKey.length?@{@"cartKey":cartKey}:nil;
    [KTHttpUtils      GET:@"cart/list.jhtml"
               parameters:parameters
                needCache:false
                needToken:false
                 progress:nil
               completion:^(id responseObject, BOOL isSuccess, NSString *message) {

                   if (![responseObject[OMDatumKey] isKindOfClass:[NSNull class]]) {
                       if (!cartKey.length) {
                           KTSystemStorageSingleton.cartKey = responseObject[OMDatumKey][OMCartKey];
                       }
                       NSArray *array =  responseObject[OMDatumKey][@"cartItems"];
                       if (isSuccess) {
                           [self startAnimating:NO];
                           if (! [array isKindOfClass:[NSNull class]]) {
                               OMCartSection *section = [OMCartSection new];
                               section.name = @"邻檬便利仓";
                               section.cartItems = [OMCartProduct mj_objectArrayWithKeyValuesArray:responseObject[OMDatumKey][@"cartItems"]];
                               for (OMCartProduct *product in section.cartItems) {
                                   product.image = [responseObject[OMImagePrefix] stringByAppendingString:product.image?:@""];
                               }
                               self.goodSections = [@[section] mutableCopy];
                               NSDictionary *sectionSelectionDict = [Storage cartSectionSelection];
                               NSDictionary *selectionDict = [Storage cartSelection];
                               _sectionSelectionDict = [NSMutableDictionary dictionaryWithDictionary:sectionSelectionDict?sectionSelectionDict:@{}];
                               _selectionDict = [NSMutableDictionary dictionaryWithDictionary:selectionDict?selectionDict:@{}];
                               [self reloadSectionSelection];
                               [self checkAllSelection];

                               KTSystemStorageSingleton.numOfCartItem = [self countCartItemNum:NO];
                               bottomBar.hidden = !(self.goodSections.count&&self.goodSections[0].cartItems.count);
                           }

                           [self.tableView reloadData];

                       }else {
                           [self showNetWorkError];
                       }

                   }else {
                       [self startAnimating:NO];
                   }
                   self.loading = NO;
               }];
}

#pragma mark - Actions
- (void)submitAction:(UIButton *)button
{
//    if (!self.deliveryInfo.id) {
//        [OMHUD HUDInfo:@"收货地址不能为空哦！"];
//        return;
//    }
    if (![Navigator showLoginViewIfUnLogin]) {
        return;
    }

    NSMutableArray *cartProducts = [NSMutableArray array];
    NSMutableArray *productIds = [NSMutableArray arrayWithCapacity:0];
    for (NSString *cartItemId in self.selectionDict.allKeys) {
        if ([self.selectionDict[cartItemId] boolValue]) {
            for (OMCartSection *cartSec in self.goodSections) {
                for (OMCartProduct *product in cartSec.cartItems) {
                    if ([cartItemId isEqualToString:product.id]) {
                        [cartProducts addObject:product];
                        [productIds addObject:product.productId];
                    }
                }
            }
        }
    }
    if (!cartProducts.count) {
        [OMHUD HUDInfo:@"请选择要结算的商品"];
        return;
    }
    NSMutableDictionary *parameter = [@{@"cartProducts":cartProducts,@"coupons":self.coupons?self.coupons:@[]} mutableCopy] ;
    if (self.deliveryInfo) {
        [parameter setObject:self.deliveryInfo forKey:@"deliveryInfo"];
    }

    [self orderCheckWithProductIds:[productIds componentsJoinedByString:@","]
                         parameter:parameter];
}


/**
 预订单检测
 */
- (void)orderCheckWithProductIds:(NSString*)productIds parameter:(NSDictionary *)parameter
{
    NSString *cartKey = KTSystemStorageSingleton.cartKey;
    [self startAnimating:true];
    [KTHttpUtils GET:@"order/checkout.jhtml"
          parameters:@{@"productIds":productIds?:@"",
                       @"cartKey":cartKey,
                       }
           needCache:false
           needToken:true
            progress:nil
          completion:^(id responseObject, BOOL isSuccess, NSString *message) {
              [self startAnimating:false];
              if (isSuccess) {
                  OMOrderBookResponse *response = [OMOrderBookResponse mj_objectWithKeyValues:responseObject[OMDatumKey]];
                  for (OMOrderItem *orderItem in response.order.orderItems) {
                      orderItem.image = [responseObject[OMImagePrefix] stringByAppendingString:orderItem.image?:@""];
                  }
                  NaviPush(@"OMOrderSubmitViewController", @{@"orderBookResponse":response});
              }else {
                  [OMHUD HUDInfo:message?:@"申请结算失败"];
              }
    }];
}

- (void)checkBoxBtnClick
{

    self.checkBoxBtn.selected = !self.checkBoxBtn.selected;
    BOOL ischeck = self.checkBoxBtn.selected;
    NSUInteger section = 0;
    for (OMCartSection *cartSec in self.goodSections) {
        [self.sectionSelectionDict setObject:@(ischeck) forKey:[@(section)stringValue]];
        for (OMCartProduct *good in cartSec.cartItems) {
            [self.selectionDict setObject:@(ischeck) forKey:good.id];
        }
        section ++;
    }
    [self checkAllSelection];
    [self.tableView reloadData];
}

#pragma mark - Getters
- (UIButton *)confirmButton
{
    if (!_confirmButton) {
        _confirmButton = [UIButton new];
        [_confirmButton setTitle:@"去结算" forState:UIControlStateNormal];
        [_confirmButton setTitleColor:SM_blackColor forState:UIControlStateNormal];
        [_confirmButton setBackgroundImage:[UIImage imageWithColor:SM_sangouColor] forState:UIControlStateNormal];
        [_confirmButton setBackgroundImage:[UIImage imageWithColor:RGBACOLOR(0, 0, 0, .26)] forState:UIControlStateDisabled];
        _confirmButton.titleLabel.font = SM_CFont(34);
        [_confirmButton addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _confirmButton;
}

- (UIButton *)checkBoxBtn
{
    if (!_checkBoxBtn) {
        _checkBoxBtn = [UIButton new];
        [_checkBoxBtn setImage:[UIImage imageNamed:@"btn_shoppingcart"] forState:UIControlStateNormal];
        [_checkBoxBtn setImage:[UIImage imageNamed:@"btn_shoppingcart_hl"] forState:UIControlStateSelected];
        [_checkBoxBtn setTitle:@"全选" forState:UIControlStateNormal];
        [_checkBoxBtn setTitleColor:SM_thumeColor forState:UIControlStateHighlighted];
        [_checkBoxBtn setTitleColor:SM_blackColor forState:UIControlStateNormal];
        [_checkBoxBtn.titleLabel setFont:SM_CFont(32)];
        [_checkBoxBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, SM_SIZE(10), 0, SM_SIZE(-10))];
        [_checkBoxBtn.imageView setContentMode:UIViewContentModeScaleAspectFit];
        [_checkBoxBtn addTarget:self action:@selector(checkBoxBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _checkBoxBtn;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[BaseTableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.delegate             = self;
        _tableView.dataSource           = self;
        _tableView.emptyDataSetSource   = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.backgroundColor      = SM_backGroundColor;
        _tableView.separatorColor = SM_naviShadowColor;
        _tableView.tableFooterView  = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.bounds.size.width, SM_SIZE(50))];
        _tableView.tableHeaderView  = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SM_SCREEN_WIDTH, SM_SIZE(20))];
    }
    return _tableView;
}


- (UILabel *)prizeLabel
{
    if (!_prizeLabel) {
        _prizeLabel = [UILabel new];
        _prizeLabel.font = SM_CFont(33);
        _prizeLabel.textAlignment = NSTextAlignmentRight;
        _prizeLabel.text = @"￥0";
        _prizeLabel.textColor = SM_redColor;
    }
    return _prizeLabel;
}

#pragma mark - Setters
- (void)setDeliveryInfo:(OMDeliveryInfo *)deliveryInfo
{
    _deliveryInfo = deliveryInfo;
    [self.addressCell configureCellWithObj:self.deliveryInfo];
}

- (void)configure
{
    self.title = @"购物车";

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.tableView registerClass:[OMShoppingcartHeaderView class] forHeaderFooterViewReuseIdentifier:[OMShoppingcartHeaderView identifier]];
    [self.tableView registerClass:[OMCartPreferentialActivityFooter class] forHeaderFooterViewReuseIdentifier:[OMCartPreferentialActivityFooter identifier]];
    self.tableView.sectionHeaderHeight = [OMShoppingcartHeaderView headerHeight];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);

    //地址选择
    UIView *deliveryContainView = [UIView new];
    deliveryContainView.backgroundColor = SM_backGroundColor;
    deliveryContainView.frame =  CGRectMake(0, 0, SM_SCREEN_WIDTH, [OMPropertyTrackByTableCell cellHeight]+SM_SIZE(20));
    self.addressCell = [OMCommonAddressTableCell new];
    self.addressCell.frame = CGRectMake(0, 0, SM_SCREEN_WIDTH, [OMPropertyTrackByTableCell cellHeight]);
    [deliveryContainView addSubview:self.addressCell];
//    self.tableView.tableHeaderView = deliveryContainView;
    deliveryContainView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapG = [UITapGestureRecognizer new];
    [deliveryContainView addGestureRecognizer:tapG];
    [[tapG rac_gestureSignal] subscribeNext:^(id x) {
        if([Navigator showLoginViewIfUnLogin]){
            NaviPush(@"OMDeliveryAddressViewController", @{@"delegate":self});
        }
    }];

    //空态
    self.emptyButtonTitle = @"去首页逛逛";
    self.emptyDataMessage = @"购物车是空的呢";
    self.emptyImage = [UIImage imageNamed:@"gouwuce"];
    [self setPrize:@"0"];

    //删除按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"ic_cart_trashCan"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(trashCanTap:)];
}

- (void)setupFooter
{
    bottomBar = [UIView new];
    bottomBar.backgroundColor = SM_whiteColor;
    [self.view addSubview:bottomBar];
    [bottomBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(@0);
        make.height.equalTo(@(49));
    }];

    [bottomBar addSubview:self.prizeLabel];
    [bottomBar addSubview:self.confirmButton];
    [bottomBar addSubview:self.checkBoxBtn];

    [self.checkBoxBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(SM_SIZE(-25)));
        make.centerY.equalTo(bottomBar.mas_centerY);
        make.height.equalTo(@(SM_SIZE(40)));
        make.width.equalTo(@(SM_SIZE(190)));
    }];

    [self.prizeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@0);
        make.top.equalTo(@1);
    }];

    [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.equalTo(@(SM_SIZE(0)));
        make.top.equalTo(@(SM_SIZE(0)));
        make.width.equalTo(@(SM_SIZE(250)));
        make.left.equalTo(self.prizeLabel.mas_right).offset(SM_SIZE(30));
    }];

    UIView *line = [UIView new];
    line.backgroundColor = SM_naviShadowColor;
    [bottomBar addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(@0);
        make.height.equalTo(@.5f);
    }];
}


#pragma mark - tableview delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.goodSections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.goodSections[section].cartItems.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OMShoppingCartGoodTableCell *cell = [OMShoppingCartGoodTableCell tableViewCellWithTableView:tableView];
    [cell configureCellWithObj:[self goodAtIndexPath:indexPath]];
    cell.delegate = self;
    cell.minNum = 1;
    cell.om_selected = [self.selectionDict[[self goodAtIndexPath:indexPath].id] boolValue];
    return  cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [OMShoppingCartGoodTableCell cellHeight];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.goodSections.count && self.goodSections[0].cartItems.count) {
        OMShoppingcartHeaderView *head = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[OMShoppingcartHeaderView identifier]];
        head.section = section;
        head.sm_selected = [self.sectionSelectionDict[[@(section)stringValue]] boolValue];
        head.delegate = self;
        [head setTitle:self.goodSections[section].name];
        return head;
    }
    return [UIView new];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    /*
     if (self.goodSections.count && self.goodSections[0].cartItems.count) {
     return [OMCartPreferentialActivityFooter new];
     }*/
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return [OMShoppingcartHeaderView headerHeight];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return DBL_EPSILON;//[OMCartPreferentialActivityFooter height];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NaviPush(@"OMGoodDetailViewController", @{@"productId":[self.goodSections[indexPath.section].cartItems[indexPath.row] productId]});
}

/*删除用到的函数*/
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle ==UITableViewCellEditingStyleDelete)
    {
        [self didClickCancelButton:nil atIndexPaths:@[indexPath]];
    }
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (OMCartProduct *)goodAtIndexPath:(NSIndexPath *)indexPath
{
    return self.goodSections[indexPath.section].cartItems[indexPath.row];
}

#pragma mark - consumeGoodTablecell delegate

#define kIndexPathCheck     if (!indexPath) {return;}
- (void)didChangeNumber:(NSUInteger)num atIndexPath:(NSIndexPath *)indexPath
{
    kIndexPathCheck;
    [self requestChangeNum:num AtIndexPath:indexPath];
}


/**
 改变购物车某个商品的数量

 @param num 数量
 @param indexPath 商品所在下标
 */
- (void)requestChangeNum:(NSUInteger)num AtIndexPath:(NSIndexPath *)indexPath
{
    NSString __block *cartKey;
    OMCartProduct *cartProduct = [self goodAtIndexPath:indexPath];
    NSUInteger previousNum = cartProduct.quantity;
    cartProduct.quantity  = num;
    [KTHttpUtils POST:@"cart/setNums.jhtml"
           parameters:[OMFMDBCartHelper parameterWithProduct:cartProduct reverseCartkey:&cartKey]
             progress:nil
           completion:^(id responseObject, BOOL isSuccess, NSString *message)
     {
         if (isSuccess) {
             [OMHUD HUDHide];
             if (!cartKey.length) {
                 cartKey = responseObject[OMDatumKey][OMCartKey];
             }
             [self goodAtIndexPath:indexPath].quantity = num;
             [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
             SMNotificationPost(OMSHOPPINGCART_BADAGE_NUM_CHANGE_NOTIFICATION, @([self countCartItemNum:NO]));
             [self setPrize];
         }else {
             [self goodAtIndexPath:indexPath].quantity = previousNum;
             [OMHUD HUDError:@"更改失败"];
         }
         [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
         [self startAnimating:NO];
     }];
}




/**
 计算数量购物车商品总数

 @return 数量
 */
- (NSUInteger)countCartItemNum:(BOOL)justSelected
{
    NSUInteger count = 0;
    for (OMCartSection *section  in self.goodSections) {
        for (OMCartProduct *product in section.cartItems) {
            if (justSelected) {
                if ([self.selectionDict[product.id] boolValue]) {
                    count += product.quantity;
                }
            }else {
                count += product.quantity;
            }
        }
    }
    return count;
}



/**
 重载选择的数据（保证数据一致性《--数量，是否选中--》）
 */
- (void)reloadSectionSelection
{
    NSUInteger section = 0;
    for (OMCartSection *cartSec in self.goodSections) {
        BOOL isAllSelected = NO;
        for (OMCartProduct *good in cartSec.cartItems) {
            isAllSelected = YES;
            if (![self.selectionDict[good.id]boolValue]) {
                isAllSelected = NO;
                break;
            }
        }
        [self.sectionSelectionDict setObject:@(isAllSelected) forKey:[@(section)stringValue]];
        section ++;
    }
}


/**
 确认删除操作的判断

 @param button btn
 @param indexPaths 下标数组
 */
- (void)didClickCancelButton:(UIButton *)button atIndexPaths:(NSArray *)indexPaths
{
    @weakify(self);
    [KTAlertView alertWithMessage:/*[self countCartItemNum:YES]?[NSString stringWithFormat:@"将要删除%li件商品?",[self countCartItemNum:YES]]:*/@"确定要删除这些商品吗？"
                            Title:nil
                     ButtonTitles:@[@"确定"]
                   withClickBlock:^(NSUInteger indexOfButton) {
                       if (indexOfButton) {
                           @strongify(self);
                           [self requestCancelCartItemAtIndexPaths:indexPaths];
                       }else {
                           isTrashExecuting = NO;
                       }
                   }];
}


static BOOL isTrashExecuting = NO;
/**
 点击垃圾筒，触发删除多项商品的事件

 @param sender btn
 */
- (void)trashCanTap:(UIButton *)sender
{
    if (isTrashExecuting) {
        return;
    }
    isTrashExecuting = YES;

    NSMutableArray *indexPaths = [@[] mutableCopy];
    NSUInteger indexOfSection = 0;
    for (OMCartSection *section in self.goodSections) {
        NSUInteger indexOfRow = 0;
        for (OMCartProduct *product in section.cartItems) {
            if ([self.selectionDict[product.id] boolValue]) {
                [indexPaths addObject:[NSIndexPath indexPathForRow:indexOfRow
                                                         inSection:indexOfSection]];
            }
            indexOfRow ++;
        }
        indexOfSection ++;
    }
    if (!indexPaths.count) {
        isTrashExecuting = NO;
        return;
    }else {
        [self didClickCancelButton:nil atIndexPaths:indexPaths];
    }
}


/**
 删除请求参数

 @param indexPaths 下标数组
 @return 参数keyvalues
 */
- (NSDictionary *)deleteParametersWithIndexPaths:(NSArray *)indexPaths idsArrayIMP:(NSMutableArray **)idsArrayIMP
{
    NSString __block *cartKey;
    *idsArrayIMP = [NSMutableArray arrayWithCapacity:indexPaths.count];
    for (NSIndexPath *indexPath in indexPaths) {
        [*idsArrayIMP addObject:[self goodAtIndexPath:indexPath].id];
    }
    NSString *idsStr = [*idsArrayIMP componentsJoinedByString:@","];
    NSMutableDictionary *parameters = [OMFMDBCartHelper parameterWithProduct:[self goodAtIndexPath:indexPaths.firstObject] reverseCartkey:&cartKey];
    [parameters removeObjectForKey:@"productId"];
    [parameters setObject:idsStr forKey:@"ids"];
    !cartKey.length?:[parameters setObject:cartKey forKey:@"cartKey"];
    [parameters removeObjectForKey:@"quantity"];
    return parameters;
}

/**
 删除购物车商品

 @param indexPaths 下标数组
 */
- (void)requestCancelCartItemAtIndexPaths:(NSArray *)indexPaths
{

    [OMHUD HUDLoading:nil];
    NSMutableArray *idsArray;
    [KTHttpUtils POST:@"cart/delete.jhtml"
           parameters:[self deleteParametersWithIndexPaths:indexPaths idsArrayIMP:&idsArray]
            needToken:false
             progress:nil
           completion:^(id responseObject, BOOL isSuccess, NSString *message)
     {
         if (isSuccess) {
             [OMHUD HUDHide];
             for (NSString *idStr in idsArray) {
                 [self.selectionDict removeObjectForKey:idStr];
                 for (OMCartSection *section in self.goodSections) {
                     for (OMCartProduct *product in section.cartItems) {
                         if ([idStr isEqualToString:product.id]) {
                             [section.cartItems removeObject:product];
                             break;
                         }
                     }
                     if (!section.cartItems.count) {
                         [self.goodSections removeObject:section];
                         break;
                     }
                 }
             }

             [self setPrize];
             [self.tableView reloadData];
             [self reloadSectionSelection];
             KTSystemStorageSingleton.numOfCartItem = [self countCartItemNum:NO];

         }else {
#ifdef DEBUG
             [OMHUD HUDInfo:message];
#else
             [OMHUD HUDError:@"删除失败!"];
#endif
             [self reloadDataFromNetWork];
         }
         isTrashExecuting = NO;
     }];
}



#pragma mark - OMShoppingcartHeaderViewDelegate

/**
 选中或取消选中 某类商品

 @param section sec
 @param ischeck 是否选中
 */
- (void)didSelectCheckBoxAtSection:(NSUInteger)section withIsCheck:(BOOL)ischeck
{
    [self.sectionSelectionDict setObject:@(ischeck) forKey:[@(section)stringValue]];
    for (OMCartProduct *good in self.goodSections[section].cartItems) {
        [self.selectionDict setObject:@(ischeck) forKey:good.id];
    }
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
    [self checkAllSelection];
}


/**
 全选事件的触发
 */
- (void)checkAllSelection
{
    BOOL isAllSectionSelected = YES;
    for (NSUInteger i = 0; i < self.goodSections.count; i ++) {
        if (![self.sectionSelectionDict[[@(i)stringValue]] boolValue]) {
            isAllSectionSelected = NO;
            break;
        }
    }
    self.checkBoxBtn.selected = isAllSectionSelected;
    //保存购物车选择项
    [Storage saveCartSectionSelection:self.sectionSelectionDict andCartSelection:self.selectionDict];
    [self setPrize];
}

/**
 分区的全选事件

 @param checkBox btn
 @param indexPath 下标
 */
- (void)didClickCheckBox:(UIButton *)checkBox atIndexPath:(NSIndexPath *)indexPath
{
    kIndexPathCheck;
    [self.selectionDict setObject:@(checkBox.selected) forKey:[self goodAtIndexPath:indexPath].id];
    BOOL isAllSelected = NO;
    for (OMCartProduct *good in self.goodSections[indexPath.section].cartItems) {
        isAllSelected = YES;
        if (![self.selectionDict[good.id]boolValue]) {
            isAllSelected = NO;
            break;
        }
    }
    [self.sectionSelectionDict setObject:@(isAllSelected) forKey:[@(indexPath.section)stringValue]];
    [self.tableView reloadData];
    [self checkAllSelection];
}


/**
 设置价格，用于显示下方的价格
 */
- (void)setPrize
{
    CGFloat prize = 0;
    NSUInteger count = 0;
    for (NSString *goodId in self.selectionDict.allKeys) {
        if ([self.selectionDict[goodId] boolValue]) {
            for (OMCartSection *cartSec in self.goodSections) {
                for (OMCartProduct *product in cartSec.cartItems) {
                    if ([goodId isEqualToString:product.id]) {
                        count += product.quantity;
                        prize += [product.price floatValue] * product.quantity;
                    }
                }
            }
        }
    }
    [self.confirmButton setTitle:count ? [NSString stringWithFormat:@"去结算(%ld)",count]:@"去结算" forState:UIControlStateNormal];
    [self setPrize:prize==0?@"0":[NSString stringWithFormat:@"%.2f",prize]];
}


- (void)setPrize:(NSString *)price
{
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc]initWithString:@"合计：" attributes:@{NSForegroundColorAttributeName:SM_blackColor}];
    if (price.length) {

        NSArray *prices = [price componentsSeparatedByString:@"."];

        if (prices.count == 2) {

            price = [[prices firstObject] stringByAppendingString:@"."];

        }
        [attri appendAttributedString:[[NSAttributedString alloc] initWithString:@""attributes:@{NSFontAttributeName:self.prizeLabel.font}]];
        NSAttributedString *priceAttri = [[NSAttributedString alloc]initWithString:price  attributes:nil];
        [attri appendAttributedString:priceAttri];

        if (prices.count == 2) {

            [attri appendAttributedString:[[NSAttributedString alloc] initWithString:[prices lastObject] attributes:nil]];

        }

        [attri appendAttributedString:[[NSAttributedString alloc] initWithString:@"元" attributes:nil]];

    }

    self.prizeLabel.attributedText = attri;

}

#pragma mark - Empty data set

/**
 点击『去首页逛逛』按钮事件的触发方法

 @param scrollView sv
 @param button btn
 */
- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button
{
    //to override
    [Navigator cancelLoginAction];
    [self.navigationController popToRootViewControllerAnimated:YES];
}


#pragma mark - OMDeliveryAddressViewCtrlDelegate
- (void)didSelectDeliveryInfo:(OMDeliveryInfo*)deliveryInfo
{
    self.deliveryInfo = deliveryInfo;
}


#pragma mark - 分隔线margin

-(void)viewDidLayoutSubviews

{

    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {

        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,SM_SIZE(100),0,0)];

    }

    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {

        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,SM_SIZE(100),0,0)];

    }

}



-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

{

    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {

        [cell setSeparatorInset:UIEdgeInsetsMake(0,SM_SIZE(100),0,0)];

    }

    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsMake(0,SM_SIZE(100),0,0)];
        
    }
    
}
@end
